﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Text.RegularExpressions;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;

using Safe_Driving.TokenUser;
using Safe_Driving.EasyCalendar.Controler;


namespace Safe_Driving
{

     public enum Type_cours_enum {
            auto_théorique = 1,
            auto_circulation = 2,
            auto_plateau = 3,
            auto_circuit = 4,
            moto_théorique = 5,
            moto_circulation = 6,
            moto_plateau = 7,
            moto_circuit = 8
        }

    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {

        public MainWindow()
        {
            InitializeComponent();
            //MessageBox.Show("" + txtPrenom.BorderBrush);

            //Récupératoin du token d'autenthification
            SingletonTokenUser token = SingletonTokenUser.GetInstance();

            //Commercial init
            if (token.User_type == SingletonTokenUser.commercial)
            {
                //Direction tab
                Intervenant_Manager.Visibility = Visibility.Collapsed;

            }
            //Moniteur init
            else
            {
                //Direction tab
                Formation_Manager.Visibility = Visibility.Collapsed;
                Material_Manager.Visibility = Visibility.Collapsed;

                //Agence tab
                New_Client_Client.Visibility = Visibility.Collapsed;
                Reserver_place_formation_Client.Visibility = Visibility.Collapsed;
                Suivis_Client.Visibility = Visibility.Collapsed;
                Inscription_exam_Client.Visibility = Visibility.Collapsed;
                Edition_facture_Client.Visibility = Visibility.Collapsed;

            }

        }

        #region Ribbon button

        //Methode pour aller à une tab
        private void goToTab(TabItem tab)
        {
            SingletonTokenUser tok = SingletonTokenUser.GetInstance();
            tok.Current_tab = tab.Name;
            tab.IsSelected = true;
        }

        private void OnCanExecute(object target, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = true;

        }

        //Click event des boutons de la tab Agence
        #region Agence

        //Evt bouton select client
        private void RibbonButton_Select_Client_Click(object sender, RoutedEventArgs e)
        {
            goToTab(SelectClientTabItem);
            populatelistBox_selectClient();
        }

        //Evt bouton new client
        private void New_Client_Click(object sender, RoutedEventArgs e)
        {
            goToTab(tab_new_user);
            //Remplire la listeBox avec les Login et Nom des client du site
            populate_usersWP();
        }

        //Evt bouton réservation de formation
        private void RibbonButton_Reservation_formation_Client_Click(object sender, RoutedEventArgs e)
        {
            goToTab(Reservation_formation_TabItem);
        }

        //Evt bouton suivis de client
        private void RibbonButton_Suivis_Client_Click(object sender, RoutedEventArgs e)
        {
            goToTab(Suivis_Client_TabItem);
            initClient();
        }

        //Evt bouton ajouter un score
        private void RibbonButton_Ajout_Score_Client_Click(object sender, RoutedEventArgs e)
        {
            goToTab(Ajout_scroe_TabItem);
        }

        //Evt bouton inscription à un exam
        private void RibbonButton_Inscription_Exam_Client_Click(object sender, RoutedEventArgs e)
        {
            goToTab(Inscription_Exam_TabItem);
            RemplirExamens();
        }

        //Evt bouton facture
        private void RibbonButton_Facture_Client_Click(object sender, RoutedEventArgs e)
        {
            //CreateInvoice();
            goToTab(Facture_TabItem);
        }

        //Evt bouton inscrpition pref
        private void RibbonButton_inscription_pref_Manager_Click(object sender, RoutedEventArgs e)
        {
            goToTab(Inscription_pref_TabItem);
            initPrefTab();
        }

        #endregion

        //Click event des boutons de la tab Direction
        #region Direction

        //Evt bouton Gestion des cours
        private void RibbonButton_Cours_Manager_Click(object sender, RoutedEventArgs e)
        {
            goToTab(cours_test);

            RemplirZones();
            RemplirTypeCours();
            RemplirFormation();
        }

        //Evt bouton Gestion des indispos des moniteurs
        private void RibbonButton_Moniteur_Manager_Click(object sender, RoutedEventArgs e)
        {
            goToTab(indispo_Moniteur_TabItem);
        }

        //Evt bouton Gestion Matériel
        private void RibbonButton_Material_Manager_Click(object sender, RoutedEventArgs e)
        {
            goToTab(gestion_materiel_TabItem);

            RemplirZonesVehicules();
           // RemplirVehicules();
        }

        #endregion








        private void Inscription_Client_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Inscription_Client_Click");
        }

        private void Suivis_Client_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Suivis_client_click");
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {


        }




        #endregion

        private void rbAuto_Checked(object sender, RoutedEventArgs e)
        {
            //dgvVehicules.Items.Clear();
            if (rbAuto.IsChecked == true)
            {
                SingletonTokenUser token = SingletonTokenUser.GetInstance();
                AppSafeDriving app = (AppSafeDriving)token.DbApp;

                var idZone = (from sfz in app.SFZone
                              where sfz.TypeZone == cbxZones.Text
                              select sfz.IDZone).Single();
                
                IEnumerable<SFVEhIcuLE> lesVoitures = (from sfv in app.SFVEhIcuLE
                                                       where sfv.TypeVEhIcuLE == "Auto" && sfv.IDZone == idZone
                                                       select sfv);


                dgvVehicules.ItemsSource = lesVoitures;
            }
        }

        private void rbTous_Checked(object sender, RoutedEventArgs e)
        {
            DateTime now = DateTime.Parse(DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second);
            
            //dgvVehicules.Items.Clear();
            if (rbTous.IsChecked == true)
            {
                SingletonTokenUser token = SingletonTokenUser.GetInstance();
                AppSafeDriving app = (AppSafeDriving)token.DbApp;

                IEnumerable<SFVEhIcuLE> lesVehicules = (from v in app.SFVEhIcuLE
                                                        //where now < v.DebutRevision
                                                        select v);
                //dgvVehicules.ItemsSource = lesVehicules;

                //IsIndisponible();
            }
        }

        private void rbMoto_Checked(object sender, RoutedEventArgs e)
        {
            //dgvVehicules.Items.Clear();
            if (rbMoto.IsChecked == true)
            {
                SingletonTokenUser token = SingletonTokenUser.GetInstance();
                AppSafeDriving app = (AppSafeDriving)token.DbApp;

                var idZone = (from sfz in app.SFZone
                              where sfz.TypeZone == cbxZones.Text
                              select sfz.IDZone).Single();


                IEnumerable<SFVEhIcuLE> lesMotos = (from sfv in app.SFVEhIcuLE
                                                    where sfv.TypeVEhIcuLE == "Moto" && sfv.IDZone == idZone
                                                    select sfv);
                dgvVehicules.ItemsSource = lesMotos;
            }
        }

        private void cbxZones_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ChargerImage();
        }

        

      
        /// <summary>
        /// Se produit lors d'une pression sur une touche du clavier lorsque la DataGrid a le focus.
        /// Permet de supprimer les véhicules sélectionnés dans la Grid de la BDD
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvVehicules_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (Keyboard.IsKeyDown(Key.Delete))
            {
                SingletonTokenUser token = SingletonTokenUser.GetInstance();
                AppSafeDriving app = (AppSafeDriving)token.DbApp;

                SFVEhIcuLE vehicule = (SFVEhIcuLE)dgvVehicules.SelectedItem;
                int id = vehicule.IDVEhIcuLE;

                var deleteVehicule = from v in app.SFVEhIcuLE
                                     where v.IDVEhIcuLE == id
                                     select v;

                foreach (var veh in deleteVehicule)
                    app.SFVEhIcuLE.DeleteOnSubmit(veh);

                try
                {
                    app.SubmitChanges();
                }
                catch (Exception)
                {
                    MessageBox.Show("Impossible de supprimer le vehicule");
                }

                RafraichirGrid();
            }
        }

        private void RafraichirGrid()
        {
            dgvVehicules.ItemsSource = null;
            string typeVehicule = string.Empty;
            
            if (rbAuto.IsChecked == true)
                typeVehicule = "Auto";
            else if (rbMoto.IsChecked == true)
                typeVehicule = "Moto";

            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;
            IEnumerable<SFVEhIcuLE> lesMotos = (from sfv in app.SFVEhIcuLE
                                                where sfv.TypeVEhIcuLE == typeVehicule
                                                select sfv);
            
            dgvVehicules.ItemsSource = lesMotos;
        }


        private void btnAjouterVehicule_Click(object sender, RoutedEventArgs e)
        {
            SingletonTokenUser tok = SingletonTokenUser.GetInstance();
            AppSafeDriving app = tok.DbApp;
            
            var idZone = (from sfz in app.SFZone
                          where sfz.TypeZone == cbxZoneVehicule.Text
                          select sfz.IDZone).Single();
            string typeVehicule = string.Empty;

            if(rb2Roues.IsChecked == true)
                typeVehicule = "Moto";
            else if (rb4Roues.IsChecked == true)
                typeVehicule = "Auto";

            SFVEhIcuLE vehicule = new SFVEhIcuLE();
            vehicule.IDZone = Convert.ToInt32(idZone);
            vehicule.Nom = txtNom.Text;
            vehicule.TypeVEhIcuLE = typeVehicule;
            vehicule.DebutRevision = DateTime.Now.AddYears(1);
            vehicule.FinRevision = DateTime.Now.AddYears(1).AddDays(3);

            try
            {
                app.SFVEhIcuLE.InsertOnSubmit(vehicule);
                app.SubmitChanges();

                MessageBox.Show("Enregistrement effectué");
                txtNomVehicule.Text = string.Empty;
            }
            catch (Exception)
            {
                MessageBox.Show("Impossible d'enregistrer le véhicule.");
            }
        }

        private void expanderAjouter_Expanded(object sender, RoutedEventArgs e)
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = token.DbApp;

            IEnumerable<string> lesZones = (from z in app.SFZone
                                            join a in app.SFAgeNcE on z.IdaGenCe equals a.IdaGenCe
                                            where a.IdaGenCe == token.Agence.IdaGenCe
                                            select z.TypeZone);

            foreach (string sfz in lesZones)
                cbxZoneVehicule.Items.Add(sfz.ToString());

            if (cbxZoneVehicule.Items.Count > 0)
                cbxZoneVehicule.SelectedIndex = 0;
        }

        
        private void btnAnnuler_Click(object sender, RoutedEventArgs e)
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = token.DbApp;

            string ligne = dgvExamens.SelectedValue.ToString();
            Match idExam = Regex.Match(ligne, "(?<tag>=)[\\s]?(?<valeur>[0-9]+)");
            try
            {
                int id = Int32.Parse(idExam.Groups["valeur"].ToString());

                var exam = from ex in app.SFPasse
                           where ex.IDClient == token.Client_selected.IDClient && ex.IDExamEn == id
                           select ex;

                foreach (var passage in exam)
                    app.SFPasse.DeleteOnSubmit(passage);

                try
                {
                    app.SubmitChanges();
                    RemplirExamens();
                }
                catch (Exception)
                {
                    MessageBox.Show("Impossible de supprimer le passage de cet examen.");
                }
            }
            catch
            {
                MessageBox.Show("Impossible de supprimer le passage de cet examen");
            }
        }

            
    }
}
